<template>
	<view>
		<!-- <text>{{formProps.placeholder || '计算结果：'}}</text> -->
		<view>
			<text style="line-height:70rpx;margin-left:20rpx;">{{_value}}</text>
		</view>
	</view>
</template>

<script setup>
	import { ref, computed, watch } from 'vue'
	// #ifndef H5
	import { Function } from 'eval5';
	// #endif

	const props = defineProps({
		formProps: {
			type: Object,
			default: () => {
				return {}
			}
		},
		formData: {
			type: Object,
			default: () => {
				return {}
			}
		},
		index: Number,
		modelValue: Number,
		
		readonly: Boolean
	})

	const _value = computed({
		get() {
			return props.modelValue
		},
		set(val) {
			emits('update:modelValue', val)
		}
	})

	const execute = ref()

	const explainStr = computed(() => {
		let explain = ''
		execute.value = null
		props.formProps.explain.forEach(item => {
			const v = String(item.symbol || item)
			if (/[0-9.]$/.test(v)) {
				explain += v
			} else {
				explain += v + ' '
			}
		})
		return explain
	})

	const emits = defineEmits(['update:modelValue'])

	function doExc() {
		// #ifndef MP-WEIXIN
		try {
			if (!(execute.value instanceof Function)) {
				if (props.formProps.isPlus) {
					const jsExplain = props.formProps.jsCode.replace(/\[\?\]/g, m => '[$_index]')
					execute.value = new Function('formData',
						`var $_index = ${props.index > 0 ? props.index - 1 : 0}; ${jsExplain} return execute(formData)`
						)
				} else {
					execute.value = new Function('formData', `return ${explainStr.value}`)
				}
			}
			let result = execute.value(props.formData)
			_value.value = props.formProps.precision > 0 ? (Number.isNaN(result) ? NaN : parseFloat(result.toFixed(props.formProps.precision))) : parseInt(result)
		} catch (e) {
			_value.value = NaN
		}
		// #endif
		// #ifdef MP-WEIXIN
		_value.value = NaN
		// #endif
	}

	watch(() => props.formData, () => {
		doExc()
	}, { deep: true })
</script>

<style>
</style>